﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Ext.Net;
using System.IO;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;

public partial class DynamicBillMode : ExtBaseData
{
    protected void Page_Load(object sender, EventArgs e)
    {
        mid = Request.Params["mid"];
        if (!X.IsAjaxRequest)
        {
            LoadMaster();
            LoadDtl();
        }
    }

    private void LoadMaster()
    {
        //加载表头 查找网格
        this.FindGridPanel.ColumnModel.Add(BuildColumns(mid, Session["UserID"].ToString(), "表头", PageHeder));
        BtnFind(null, null);
    }

    private void LoadDtl()
    {
        //加载明细网格
        this.GridPanel1.ColumnModel.Add(BuildColumns(mid, Session["UserID"].ToString(), "明细", DtlEditPanel));
        //SetToolbarState("Browse");
        StoreColumns(MainStore, mid, "明细");
        var sql= mydb.DM_GetExecuteScalarObj("select weburl from sys_modules where parentid=" + mid + " and modulecode='明细'").ToString();
        ViewState["sqlDtl"] = sql;
        MainStore.DataSource = mydb.DM_GetDateSet(sql + " where billno =''");
        MainStore.DataBind();
    }

    protected void SetToolbarState(string state)
    {
        this.btnAdd.Disabled = !(state=="Browse");
        this.btnEdit.Disabled = !(state == "Browse" || this.btnCheck1.Disabled);
        this.btnSave.Disabled = !(state != "Browse");
        this.btnCancel.Disabled = !(state != "Browse");
        this.btnDelete.Disabled = !(state == "Browse" || this.btnCheck1.Disabled || this.FindStore.Data != null);
        this.btnFind.Disabled = !(state == "Browse");
        this.btnCheck1.Disabled = !(state == "Browse");
        this.btnCheckLog.Disabled = !(state == "Browse");
    }
    protected void MyData_Refresh(object sender, StoreReadDataEventArgs e)
    {
        
    }

    protected void BtnFind(object sender, DirectEventArgs e)
    {
        this.TabPanel1.ActiveIndex = 1;
        StoreColumns(FindStore, mid,"表头");
        string sql="";
        sql = mydb.DM_GetExecuteScalarObj("select weburl from sys_modules where parentid="+mid+" and modulecode='表头'").ToString();
        ViewState["sqlMaster"] = sql;
        FindStore.DataSource = mydb.DM_GetDateSet(sql);
        FindStore.DataBind();
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void BtnAdd()
    {
        //明细新增事件处理，处理字段默认值
        HI_billNO.Value = mydb.DM_GetExecuteScalarObj("exc_getcustorno 'RQ','bus_requestmst','billno','3'").ToString();
        if (this.PageHeder.FindControl("txtBillNo")!=null)
            (this.PageHeder.FindControl("txtBillNo") as TextField).Text = HI_billNO.Value.ToString();
        MainStore.DataSource = mydb.DM_GetDateSet(ViewState["sqlDtl"].ToString()+" where billno=''");
        MainStore.DataBind();
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void BtnSave(string fields, string vals,string dtlOjb)
    {
        //单据头数据保存
        //fields = fields.TrimEnd(',');
        //vals = vals.TrimEnd(',');
        RowSelectionModel sm = this.FindGridPanel.GetSelectionModel() as RowSelectionModel;
        string id = sm.SelectedRecordID;
        //ShowBox("ID:" + id);
        string sql = "";
        string tablename = "bus_requestmst";
        string keyname = "BillNo";
        //新增
        if (this.ActState.Value.ToString() == "Add")
        {
            string[] flist = fields.Split(',');
            string[] vlist = vals.Split(',');
            string flstr = "", valstr = "", tempstr = "";
            for (int i = 0; i < flist.Length; i++)
            {
                flstr += flist[i] + ",";
                if (vlist[i] == "")
                {
                    tempstr = "''";
                }
                else if (vlist[i].ToLower() == "true")
                {
                    tempstr = "1";
                }
                else if (vlist[i].ToLower() == "false")
                {
                    tempstr = "0";
                }
                else
                {
                    tempstr = "'" + vlist[i] + "'";
                }
                valstr += tempstr + ",";
            }
            flstr = flstr.TrimEnd(',');
            valstr = valstr.TrimEnd(',');
            sql = "insert into " + tablename + "(" + flstr + ")values(" + valstr + ") ";
        }
        else
        {
            //修改

            string[] flist = fields.Split(',');
            string[] vlist = vals.Split(',');
            string flstr = "", tempstr = "";
            for (int i = 0; i < flist.Length; i++)
            {
                if (vlist[i] == "")
                {
                    tempstr = "''";
                }
                else if (vlist[i].ToLower() == "true")
                {
                    tempstr = "1";
                }
                else if (vlist[i].ToLower() == "false")
                {
                    tempstr = "0";
                }
                else
                {
                    tempstr = "'" + vlist[i] + "'";
                }
                flstr += flist[i] + "=" + tempstr + ",";
            }
            flstr = flstr.TrimEnd(',');
            sql = "update " + tablename + " set " + flstr + " where " + keyname + " = '" + id + "' ";
        }
        SaveDtlByGrid(sql, dtlOjb);
        //X.Msg.Alert("Submit", sql).Show();
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void SaveDtlByGrid(string sql,string ojb)
    {
        string tablename = "bus_requestdtl";
        string keyname = "Maxid";

        //ShowBox("ID:" + id
        //Newtonsoft.Json.JsonReader reader = new JsonTextReader(new StringReader(ojb.ToString()));
        //while (reader.Read())
        //{
        //    sql += reader.Value + ":";
        //}
        JObject jo = (JObject)JsonConvert.DeserializeObject(ojb);
        int k = 1;
        if (jo["Updated"] != null)
        {
            JArray ja = (JArray)JsonConvert.DeserializeObject(jo["Updated"].ToString());
            for (int i = 0; i < ja.Count; i++)
            {
                sql += "update " + tablename + " set ";
                Newtonsoft.Json.JsonReader reader = new JsonTextReader(new StringReader(ja[i].ToString()));
                while (reader.Read())
                {
                    if (reader.Value != null)
                    {
                        if (0 != k % 2)
                        {
                            sql += reader.Value + "=";
                        }
                        else
                        {
                            sql += "'"+reader.Value + "',";
                        }
                        k++;
                    }
                }
                sql = sql.TrimEnd(',')+" where billno = '"+this.HI_billNO.Value.ToString()+"' and "+keyname+"='"+ja[i][keyname]+"' ";
            }

        }
        if (jo["Created"] != null)
        {
            string flds = "";
            string vals = "";
            JArray ja = (JArray)JsonConvert.DeserializeObject(jo["Created"].ToString());
            for (int i = 0; i < ja.Count; i++)
            {
                flds = "";
                vals = "";
                sql += "insert into "  + tablename + "(";
                Newtonsoft.Json.JsonReader reader = new JsonTextReader(new StringReader(ja[i].ToString()));
                while (reader.Read())
                {
                    if (reader.Value != null)
                    {
                        if (0 != k % 2)
                        {
                            flds += reader.Value + ",";
                        }
                        else
                        {
                            vals += "'" + reader.Value + "',";
                        }
                        k++;
                    }
                }
                sql += flds.TrimEnd(',') + ")values(" + vals.TrimEnd(',') + ") ";
            }
        }
        if (jo["Deleted"] != null)
        {
            JArray ja = (JArray)JsonConvert.DeserializeObject(jo["Deleted"].ToString());
            for (int i = 0; i < ja.Count; i++)
            {
                sql += " delete from " + tablename + " where billno ='"+this.HI_billNO.Value.ToString()+"' and " + keyname + "='" + ja[i][keyname] + "'";
            }
        }
        //ShowBox(sql.ToString());
        if (mydb.ExecuteNonQueryTran(sql))
        {
            ShowBox("保存成功！");
            MainStore.CommitChanges();
        }
        else
        {
            ShowBox("保存失败！");
        }
    }
    protected void SaveClick(object sender, DirectEventArgs e)
    {
        string JsonData = e.ExtraParams["data"].ToString();
        string sql = "";
        
        ShowBox(JsonData);
    }
    [DirectMethod(Namespace = "CompanyX")]
    public void OpenDtl(string billno)
    {
        StoreColumns(MainStore, mid, "明细");
        string sql = ViewState["sqlDtl"].ToString();
        MainStore.DataSource = mydb.DM_GetDateSet(sql + " where billno ='" + billno+"'");
        MainStore.DataBind();
    }
}